// 自定义图片动效模块 - 增强版
function initCustomImageEffect(canvas, imageUrl) {
    console.log('initCustomImageEffect called');
    console.log('Parameters received:');
    console.log('- canvas:', canvas ? 'canvas element exists' : 'NO CANVAS!');
    console.log('- imageUrl parameter:', imageUrl);
    console.log('- window.backgroundImageUrl:', window.backgroundImageUrl);
    
    // 确保canvas存在
    if (!canvas) {
        console.error('Canvas element not provided to initCustomImageEffect!');
        return;
    }
    
    // 获取2D渲染上下文
    const ctx = canvas.getContext('2d');
    if (!ctx) {
        console.error('Failed to get canvas 2D context!');
        return;
    }
    
    // 动画和状态变量
    let opacity = 0;
    let transitionActive = false;
    let loadingSpinnerAngle = 0;
    let loadingAnimationId = null;
    let animationId = null;
    let img = null;
    
    // 优先使用传入的imageUrl参数，然后再使用window.backgroundImageUrl
    const finalImageUrl = imageUrl || window.backgroundImageUrl;
    console.log('Final image URL to load:', finalImageUrl || 'No URL provided!');
    
    // 设置默认深色背景
    function setDefaultBackground() {
        ctx.fillStyle = 'hsl(220, 40%, 5%)'; // 深蓝色背景
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 添加柔和的渐变边框
        drawGradientBorder(canvas, ctx);
        
        // 显示提示文字
        ctx.fillStyle = `rgba(255, 255, 255, ${opacity * 0.8})`; // 透明度随过渡效果变化
        ctx.font = 'bold 20px Arial, sans-serif';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        
        // 添加文字阴影增强可读性
        ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
        ctx.shadowBlur = 5;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 2;
        
        ctx.fillText('自定义背景图片', canvas.width / 2, canvas.height / 2);
        
        if (finalImageUrl) {
            ctx.fillStyle = `rgba(255, 255, 255, ${opacity * 0.5})`;
            ctx.font = '14px Arial, sans-serif';
            ctx.fillText(`加载图片中: ${finalImageUrl.substring(finalImageUrl.lastIndexOf('/') + 1)}`, canvas.width / 2, canvas.height / 2 + 30);
        } else {
            ctx.fillStyle = `rgba(255, 255, 255, ${opacity * 0.7})`;
            ctx.font = '14px Arial, sans-serif';
            ctx.fillText('请在配置中上传背景图片', canvas.width / 2, canvas.height / 2 + 30);
        }
        
        // 重置阴影设置
        ctx.shadowColor = 'transparent';
        ctx.shadowBlur = 0;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
    }
    
    // 绘制渐变边框
    function drawGradientBorder(canvas, ctx) {
        const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height);
        gradient.addColorStop(0, 'rgba(100, 149, 237, 0.2)');
        gradient.addColorStop(0.5, 'rgba(100, 149, 237, 0.05)');
        gradient.addColorStop(1, 'rgba(100, 149, 237, 0.2)');
        
        const borderWidth = 15;
        // 绘制上下边框
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, borderWidth);
        ctx.fillRect(0, canvas.height - borderWidth, canvas.width, borderWidth);
        
        // 绘制左右边框
        const sideGradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
        sideGradient.addColorStop(0, 'rgba(100, 149, 237, 0.2)');
        sideGradient.addColorStop(0.5, 'rgba(100, 149, 237, 0.05)');
        sideGradient.addColorStop(1, 'rgba(100, 149, 237, 0.2)');
        
        ctx.fillStyle = sideGradient;
        ctx.fillRect(0, 0, borderWidth, canvas.height);
        ctx.fillRect(canvas.width - borderWidth, 0, borderWidth, canvas.height);
    }
    
    // 移除加载动画，避免白色圆圈问题
    function drawLoadingSpinner() {
        // 不再绘制任何加载动画元素
        // 仅在控制台记录加载状态
        console.log('Loading background image...');
        
        // 继续动画以保持状态更新
        loadingAnimationId = requestAnimationFrame(drawLoadingSpinner);
    }
    
    // 开始淡入效果
    function startFadeIn() {
        transitionActive = true;
        opacity = 0;
        
        function animateFade() {
            opacity += 0.05;
            
            if (img && img.complete) {
                drawImage();
                // 确保加载动画已停止
                if (loadingAnimationId) {
                    cancelAnimationFrame(loadingAnimationId);
                    loadingAnimationId = null;
                }
            } else {
                setDefaultBackground();
                // 不再调用drawLoadingSpinner以避免白色圆圈
            }
            
            if (opacity < 1) {
                requestAnimationFrame(animateFade);
            } else {
                opacity = 1;
                transitionActive = false;
                
                // 清除加载动画
                if (loadingAnimationId) {
                    cancelAnimationFrame(loadingAnimationId);
                    loadingAnimationId = null;
                }
            }
        }
        
        animateFade();
    }
    
    // 图片加载错误处理 - 增强版
    function handleImageError(error) {
        // 清除加载动画
        if (loadingAnimationId) {
            cancelAnimationFrame(loadingAnimationId);
            loadingAnimationId = null;
        }
        
        console.error('FAILED to load custom background image!', error);
        
        // 收集详细错误信息
        const errorDetails = {
            url: finalImageUrl,
            errorType: error.type || 'Unknown',
            errorMessage: error.message || 'Failed to load resource',
            timestamp: new Date().toISOString()
        };
        
        console.log('Error details:', errorDetails);
        
        // 清除画布
        ctx.fillStyle = 'hsl(220, 40%, 5%)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 添加渐变边框
        drawGradientBorder(canvas, ctx);
        
        // 显示错误信息
        ctx.fillStyle = `rgba(255, 255, 255, ${opacity * 0.8})`;
        ctx.font = 'bold 20px Arial, sans-serif';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('自定义背景图片', canvas.width / 2, canvas.height / 2 - 50);
        
        ctx.fillStyle = `rgba(255, 0, 0, ${opacity * 0.8})`;
        ctx.font = '16px Arial, sans-serif';
        ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
        ctx.shadowBlur = 3;
        ctx.fillText('图片加载失败', canvas.width / 2, canvas.height / 2);
        
        // 显示图片URL（截断显示）
        const displayUrl = finalImageUrl.length > 40 ? finalImageUrl.substring(finalImageUrl.lastIndexOf('/') + 1) : finalImageUrl;
        ctx.fillStyle = `rgba(255, 255, 255, ${opacity * 0.6})`;
        ctx.font = '12px Arial, sans-serif';
        ctx.fillText(displayUrl, canvas.width / 2, canvas.height / 2 + 25);
        
        // 重置阴影设置
        ctx.shadowColor = 'transparent';
        ctx.shadowBlur = 0;
        
        // 添加重试按钮提示
        const retryButtonX = canvas.width / 2 - 60;
        const retryButtonY = canvas.height / 2 + 50;
        const retryButtonWidth = 120;
        const retryButtonHeight = 35;
        
        // 绘制按钮背景
        ctx.beginPath();
        ctx.roundRect(retryButtonX, retryButtonY, retryButtonWidth, retryButtonHeight, 5);
        ctx.fillStyle = `rgba(70, 130, 180, ${opacity * 0.8})`;
        ctx.fill();
        ctx.strokeStyle = `rgba(100, 149, 237, ${opacity * 1})`;
        ctx.lineWidth = 2;
        ctx.stroke();
        
        // 绘制按钮文字
        ctx.fillStyle = `rgba(255, 255, 255, ${opacity * 0.9})`;
        ctx.font = '14px Arial, sans-serif';
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText('重新加载', canvas.width / 2, canvas.height / 2 + 67.5);
        
        // 添加点击重试功能
        canvas.style.cursor = 'pointer';
        canvas.onclick = function() {
            loadImage();
            canvas.style.cursor = 'default';
            canvas.onclick = null;
        };
    }
    
    // 绘制图片到画布 - 增强版，确保F12时不丢失
    function drawImage() {
        // 检查canvas和ctx是否存在
        if (!canvas || !ctx) {
            console.error('Canvas or context not available for drawing');
            return;
        }
        
        if (!img || !img.complete) {
            setDefaultBackground();
            return;
        }
        
        // 强制设置canvas尺寸，确保在DOM变化后正确更新
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        canvas.style.width = window.innerWidth + 'px';
        canvas.style.height = window.innerHeight + 'px';
        
        // 重置上下文状态
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        
        try {
            // 保存当前状态
            ctx.save();
            
            // 设置全局透明度，用于过渡效果
            ctx.globalAlpha = opacity;
            
            // 提高图片渲染质量
            ctx.imageSmoothingEnabled = true;
            ctx.imageSmoothingQuality = 'high';
            
            // 计算图片的缩放比例以适应画布
            const scale = Math.max(canvas.width / img.width, canvas.height / img.height) * 1.02; // 轻微放大以确保没有黑边
            const newWidth = img.width * scale;
            const newHeight = img.height * scale;
            const x = (canvas.width - newWidth) / 2;
            const y = (canvas.height - newHeight) / 2;
            
            console.log('Calculated draw parameters:');
            console.log('- scale:', scale);
            console.log('- new dimensions:', newWidth, 'x', newHeight);
            console.log('- position:', x, ',', y);
            
            // 绘制图片
            ctx.drawImage(img, x, y, newWidth, newHeight);
            
            // 添加轻微的暗色叠加层以提高文字可读性（使用渐变效果更自然）
            const gradientOverlay = ctx.createRadialGradient(
                canvas.width / 2, canvas.height / 2, 0,
                canvas.width / 2, canvas.height / 2, Math.max(canvas.width, canvas.height) / 2
            );
            gradientOverlay.addColorStop(0, 'rgba(0, 0, 0, 0.05)');
            gradientOverlay.addColorStop(0.7, 'rgba(0, 0, 0, 0.15)');
            gradientOverlay.addColorStop(1, 'rgba(0, 0, 0, 0.2)');
            
            ctx.fillStyle = gradientOverlay;
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            
            // 恢复状态
            ctx.restore();
            
            console.log('Image drawn to canvas successfully!');
            
        } catch (e) {
            console.error('Error drawing image:', e);
            setDefaultBackground();
            cleanup();
        }
    }
    
    // 加载图片 - 增强版
    function loadImage() {
        // 清除之前可能存在的加载动画
        if (loadingAnimationId) {
            cancelAnimationFrame(loadingAnimationId);
            loadingAnimationId = null;
        }
        
        // 不再显示任何加载动画以避免白色圆圈问题
        
        if (!finalImageUrl) {
            setDefaultBackground();
            return;
        }
        
        // 清理之前的图片对象
        if (img) {
            img.onload = null;
            img.onerror = null;
            img.onabort = null;
            img = null;
        }
        
        img = new Image();
        // 允许跨域图片使用
        img.crossOrigin = 'anonymous';
        
        // 详细的加载日志
        console.log('Creating Image object for URL:', finalImageUrl);
        
        // 添加超时处理
        const timeoutId = setTimeout(() => {
            if (img && !img.complete) {
                console.error('Image loading timed out');
                img.src = ''; // 停止加载
                handleImageError({ type: 'timeout', message: 'Loading timed out' });
            }
        }, 10000); // 10秒超时
        
        img.onload = function() {
            clearTimeout(timeoutId);
            console.log('Image loaded successfully!');
            console.log('Image dimensions:', img.width, 'x', img.height);
            console.log('Canvas dimensions:', canvas.width, 'x', canvas.height);
            // 开始淡入效果
            startFadeIn();
        };
        
        // 添加错误事件
        img.onerror = function(event) {
            clearTimeout(timeoutId);
            handleImageError(event);
        };
        
        img.onabort = function() {
            clearTimeout(timeoutId);
            console.warn('Image loading aborted!');
        };
        
        // 设置图片源
        console.log('Setting image src:', finalImageUrl);
        img.src = finalImageUrl;
    }
    
    // 资源清理
    function cleanup() {
        if (animationId) {
            cancelAnimationFrame(animationId);
            animationId = null;
        }
        
        if (loadingAnimationId) {
            cancelAnimationFrame(loadingAnimationId);
            loadingAnimationId = null;
        }
        
        // 清理图片对象
        if (img) {
            img.onload = null;
            img.onerror = null;
            img.onabort = null;
            img = null;
        }
        
        // 清理事件监听
        canvas.onclick = null;
        canvas.style.cursor = 'default';
    }
    
    // 初始化
    setDefaultBackground();
    if (finalImageUrl) {
        loadImage();
    }
    
    // 立即尝试绘制背景，避免初始状态下的空白或白色圆圈
    if (canvas && ctx) {
        ctx.fillStyle = 'hsl(220, 40%, 5%)'; // 深蓝色背景
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }
    
    // 设置窗口大小变化事件处理 - 修复F12时图片丢失问题
    window.addEventListener('resize', function handleResize() {
        // 清除之前可能存在的动画
        if (animationId) {
            cancelAnimationFrame(animationId);
            animationId = null;
        }
        
        // 延迟执行，确保DOM更新完成
        setTimeout(function() {
            // 确保canvas尺寸正确更新
            if (canvas) {
                canvas.width = window.innerWidth;
                canvas.height = window.innerHeight;
                canvas.style.width = window.innerWidth + 'px';
                canvas.style.height = window.innerHeight + 'px';
            }
            
            // 强制重绘图片，解决F12开发者工具打开时图片丢失的问题
            if (img && img.complete) {
                drawImage();
            } else if (!transitionActive) {
                startFadeIn();
            }
        }, 50);
    });
    
    // 添加可见性变化事件处理，确保页面从后台回到前台时图片正确显示
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden && img && img.complete) {
            // 页面变为可见时，强制重绘图片
            setTimeout(drawImage, 100);
        }
    });
    
    // 添加focus事件处理，确保窗口获得焦点时图片正确显示
    window.addEventListener('focus', function() {
        if (img && img.complete) {
            setTimeout(drawImage, 100);
        }
    });
    
    // 添加DOMContentLoaded事件，确保DOM完全加载后重新绘制
    document.addEventListener('DOMContentLoaded', function() {
        if (img && img.complete) {
            setTimeout(drawImage, 100);
        }
    });
    
    // 添加延迟重绘循环，确保在任何DOM变化后图片都能正确显示
    function startRedrawLoop() {
        if (img && img.complete) {
            drawImage();
        }
        // 每500毫秒检查一次并重绘，这是一个安全机制
        setTimeout(startRedrawLoop, 500);
    }
    // 启动安全重绘循环
    startRedrawLoop();
    
    // 添加MutationObserver监听DOM变化，确保在DOM变化时重绘
    const observer = new MutationObserver(function(mutations) {
        // 仅在必要时重绘
        if (img && img.complete && !transitionActive) {
            setTimeout(drawImage, 50);
        }
    });
    
    // 监听整个文档的DOM变化
    observer.observe(document.body, {
        childList: true,
        subtree: true,
        attributes: true,
        characterData: true
    });
    
    // 确保在图片加载完成后立即重绘
    if (img && img.complete) {
        drawImage();
    }
    
    // 返回清理函数，便于外部调用
    return cleanup;
}

// 暴露函数到全局作用域
window.initCustomImageEffect = initCustomImageEffect;